package com.ibeetl.admin.core.web;

import com.ibeetl.admin.core.entity.CoreOrg;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.entity.VerifyCode;
import com.ibeetl.admin.core.rbac.UserLoginInfo;
import com.ibeetl.admin.core.rbac.tree.MenuItem;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.service.CoreUserService;
import com.ibeetl.admin.core.service.RedisService;
import com.ibeetl.admin.core.util.HttpRequestLocal;
import com.ibeetl.admin.core.util.VerifyCodeGenUtils;
import com.sdx.exception.LoginFailException;
import com.sdx.exception.LoginFailExceptionCode;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Enumeration;

@Controller
public class IndexController {

	@Autowired
	CorePlatformService platformService;

	@Autowired
	CoreUserService userService;

	@Autowired
	HttpRequestLocal httpRequestLocal;

	@Resource
	private RedisService redisService;

	@RequestMapping("/")
	public ModelAndView login() {
		ModelAndView view = new ModelAndView("/login.html");
		return view;
	}

	@PostMapping("/login.do")
	@ResponseBody
	public JsonResult login(String code, String password,String username,HttpServletRequest request){
		if(request.getSession().getAttribute("VerifyCode")==null){
			throw new LoginFailException(LoginFailExceptionCode.LOGIN_CODE,"验证码错误");
		}
		String verifyCode = request.getSession().getAttribute("VerifyCode").toString();
		request.getSession().removeAttribute("VerifyCode");
		if(!code.equalsIgnoreCase(verifyCode)){
			throw new LoginFailException(LoginFailExceptionCode.LOGIN_CODE,"验证码错误");
		}
		UserLoginInfo info = userService.login(username, password);
		if (info == null) {
			throw new LoginFailException(LoginFailExceptionCode.NOT_FOUND,"用户名密码错");
		}

		CoreUser user = info.getUser();
		CoreOrg currentOrg = info.getOrgs().get(0);
		for (CoreOrg org : info.getOrgs()) {
			if (org.getId() == user.getOrgId()) {
				currentOrg = org;
				break;
			}
		}

		info.setCurrentOrg(currentOrg);
		// 记录登录信息到session
		this.platformService.setLoginUser(info.getUser(), info.getCurrentOrg(), info.getOrgs());
		ModelAndView view = new ModelAndView("redirect:/index.do");
		JsonResult result = JsonResult.success();
		result.setData("index.do");
		return result;
	}

	@RequestMapping("/index.do")
	public ModelAndView index() {
		ModelAndView view = new ModelAndView("/index.html");
		CoreUser currentUser = platformService.getCurrentUser();
		Long orgId = platformService.getCurrentOrgId();
		MenuItem menuItem = platformService.getMenuItem(currentUser.getId(), orgId);
		view.addObject("menus", menuItem);
		return view;
	}

	@RequestMapping("/logout.do")
	public ModelAndView logout(HttpServletRequest request) {
		HttpSession session = request.getSession();
		Enumeration eum = session.getAttributeNames();
		while(eum.hasMoreElements()) {
			String key = (String)eum.nextElement();
			session.removeAttribute(key);
		}
		ModelAndView view = new ModelAndView("redirect:/");
		return view;
	}
	@RequestMapping("/changeOrg.do")
	public ModelAndView changeOrg(HttpServletRequest request,Long orgId) {
		platformService.changeOrg(orgId);
		ModelAndView view = new ModelAndView("redirect:/index.do");
		return view;
	}


	@GetMapping("/verifyCode")
	public void verifyCode(HttpServletRequest request, HttpServletResponse response) {

		try {
			//设置长宽
			VerifyCode verifyCode = VerifyCodeGenUtils.generate(80, 28);
			String code = verifyCode.getCode();
			//将VerifyCode绑定session
			System.out.println(code);
			request.getSession().setAttribute("VerifyCode", code);
			//设置响应头
			response.setHeader("Pragma", "no-cache");
			//设置响应头
			response.setHeader("Cache-Control", "no-cache");
			//在代理服务器端防止缓冲
			response.setDateHeader("Expires", 0);
			//设置响应内容类型
			response.setContentType("image/jpeg");
			response.getOutputStream().write(verifyCode.getImgBytes());
			response.getOutputStream().flush();
		} catch (IOException e) {

		}
	}

	/**
	 *
	 * @param type 1 key    2 list key
	 * @param key
	 * @return
	 */

	@RequestMapping("/redis/queryValueByKey")
	@ResponseBody
	public JsonResult queryValueByKey(@RequestParam Integer type,@RequestParam String key) {
		JsonResult result = JsonResult.success();
		if(StringUtils.isNotEmpty(key)&&type!=null){
			if(type==1){
				result.setData(redisService.getValue(key, false));
			}else if(type == 2){
				System.out.println(StringUtils.join(redisService.getList(key),","));
				result.setData(redisService.getList(key));
			}
		}
		return result;
	}

}
